//addcolor
$(addColor);
function addColor() {
	$('#userTbody tr').removeClass();
	for(var i = 0; i < $('#userTbody tr').length; i++) {
		if(i % 4 == 0) {
			$('#userTbody tr').eq(i).addClass('info');
		}
		if(i % 4 == 1) {
			$('#userTbody tr').eq(i).addClass('success');
		}
		if(i % 4 == 2) {
			$('#userTbody tr').eq(i).addClass('warning');
		}
		if(i % 4 == 3) {
			$('#userTbody tr').eq(i).addClass('active');
		}
	}
}//addcolor end

//choose all and choose more
$(chooseAll);
function chooseAll() {
	$("#btn").click(function() {
		$("input[name='a']").prop("checked", this.checked);
	});
	$("input[name='a']").click(function() {
		var $subs = $("input[name='a']");
		$("#btn").prop("checked", $subs.length == $subs.filter(":checked").length ? true : false);
	});
}// choose all and choose more end

// delete choose delete more
$('#deleteAll').on('click', function() {
	deleteChoose();
	addColor();
});
function deleteChoose() {
	if (confirm("确定删除吗？") == true) {
		var students = [];
		$("tbody input:checked").each(function () {
			var $row = $(this).closest('tr'); // 获取包含删除按钮的行  
			var studentNum = $row.find('td:eq(1)').text().trim(); // 从第二列（学号列）获取学号  
			var data = {
				id: examId
			};
			exam.push(data);
		});
		var json = JSON.stringify(exam);
		$.ajax({
			type: 'POST',                       //请求方式
			url: '/exam-manage/deleteexam',  //请求的URL地址
			data: json,
			processData: false,
			contentType: false,
			success: location.reload(),
			error: function (xhr, status, error) { // 添加错误处理函数  
				alert("删除失败！")
				console.error("请求失败: " + error);
			}
		})
	}
	$("#btn").prop("checked", false);
}// delete choose delete more end

// delete one
$('.deleteOne').click(deleter);
function deleter() {
	if (confirm("确定删除吗？") == true) {
		var $row = $(this).closest('tr'); // 获取包含删除按钮的行  
		var ExamId = $row.find('td:eq(1)').text().trim(); // 从第二列（学号列）获取学号  
		var data = {
			'examId': ExamId
		};
		$.ajax({
			type: 'POST',                       //请求方式
			url: '/exam-manage/deleteexam',  //请求的URL地址
			data: data,
			datatype: "json",
			success: function (response) {
				location.reload();
			},
			error: function (xhr, status, error) { // 添加错误处理函数  
				alert("删除失败！")
				console.error("请求失败: " + error);
			}
		})
	}
}
$('.deleteOne').click(deleter);// delete one end



//添加
$('.add-manage').on("click",function (){
	popupManager("add-manage");
	managerMarch();
});
//修改
$('.changeInfrom').on("click", changeInfo);
function changeInfo(e) {
	var formdata = {
		ExamID: $('#inputExamId').val(),
			Examcourse: $('#inputExamCourse').val(),
			ExamMonth: $('#inputExamMonth').val(),
			ExamDay: $('#inputExamDay').val(),
			ExamHour: $('#inputExamHour').val(),
			ExamMinute: $('#inputExamMinute').val()
	};
	console.log(formdata);
	$.ajax({
		type: 'POST',                       //请求方式
		url: '/exam-manage/changeExam',  //请求的URL地址
		data: formdata,
		datatype: "json",
		success: function (response) {
			if (response.status == success) {
				location.reload();
				addColor();

			}
			else { //请求成功后的回调函数
				console.log(formdata);
			}
		},
		error: function (xhr, status, error) { // 添加错误处理函数  
			alert("修改失败！")
			console.error("请求失败: " + error);
		}
	})
	popup("changeManager");
	march();
}
function popupManager(id){
	$('#zz').css('display', 'block');
	$('#addUser').css('display', 'block');
	if(id == "add-manage"){
		$('#addManageInform').removeClass("changeManage");
		$('#addManageInform').addClass("addManage");
	}
	if(id == "changeManager"){
		$('#addManageInform').removeClass("addManage");
		$('#addManageInform').addClass("changeManage");
	}
}

$(function () {

	$('.form-horizontal').on('submit', function (e) {
		e.preventDefault()                  // 2.阻止表单的默认行为
		var formdata = {
			ExamID: $('#inputExamId').val(),
			Examcourse: $('#inputExamCourse').val(),
			ExamMonth: $('#inputExamMonth').val(),
			ExamDay: $('#inputExamDay').val(),
			ExamHour: $('#inputExamHour').val(),
			ExamMinute: $('#inputExamMinute').val()
		};
		$.ajax({
			type: 'POST',                       //请求方式
			url: '/exam-manage/addexam',  //请求的URL地址
			data: formdata,
			datatype: "json",
			success: function (response) {
				location.reload();
			},
			error: function (xhr, status, error) { // 添加错误处理函数  
				alert("添加失败！")
				console.error("请求失败: " + error);
			}
		})
	})
})
function addManagerEnter() {
			 	//添加至下一行
                $('table tr:last').after($('<tr><td class="checkbox m-0"><label><input type="checkbox" name="a"></label></td><td></td><td></td><td></td><td><i class="fa fa-trash-o cur-p deleteOne"></i>/<i class="fa fa-edit changeManager"></i></td></tr>'));
                $('table tr:last td:eq(1)').text($('#inputExamId').val());
                $('table tr:last td:eq(2)').text($('#inputExamCourse').val());
            	$('table tr:last td:eq(3)').text($('#inputExamTime').val());
            	$('table tr:last td:eq(4)').find(".deleteOne").click(deleter);
				$('table tr:last td:eq(4)').find(".changeManager").click(changeManager);
				colseZz();
        }
function changeManagerEnter(trobject){
			trobject.find('td:eq(1)').text($('#inputExamId').val());
			trobject.find('td:eq(2)').text($('#inputExamCourse').val());
			trobject.find('td:eq(3)').text($('#inputExamTime').val());
			colseZz();
		};
		

//close and cancel
$('#cancelChange').click(colseZz);
$('#addClose').click(colseZz);
function colseZz() {
	$('#zz').css('display', 'none');
	$('#addUser').css('display', 'none');
}
//close and cancel end

function manageTabke(manageInfo){
	for(var i in manageInfo){
							$('tbody').append($('<tr><td class="checkbox m-0"><label><input type="checkbox" name="a"></label></td><td></td><td></td><td></td><td><i class="fa fa-trash-o cur-p deleteOne"></i>/<i class="fa fa-edit changeManager"></i></td></tr>'));
							$('tbody tr:last td:eq(1)').html(manageInfo[i]["ExamId"]);
							$('tbody tr:last td:eq(2)').html(manageInfo[i]["ExamCourse"]);
							$('tbody tr:last td:eq(3)').html(manageInfo[i]["ExamTime"]);
							$('table tr:last td:eq(4)').find(".deleteOne").click(deleter);
							$('table tr:last td:eq(4)').find(".changeManager").click(changeManager);
							colseZz();
							addColor();
	}
}
$(document).ready(function fetchData() {
	$.ajax({
		url: '/exam-manage/getexam', // 假设的API URL  
		type: 'get',
		dataType: 'json',
		success: function (data) {
			// 清空表格数据（如果需要）  
			$('#userTbody').empty();

			// 遍历数据并插入到表格中  
			data.forEach(function (exam) {
				var row = $('<tr></tr>');
				row.append($('<td class="checkbox m-0"><label><input type="checkbox" name="a"></label></td>'));
				row.append($('<td></td>').text(exam.ExamId));
				row.append($('<td></td>').text(exam.ExamCourse));
				row.append($('<td></td>').text(exam.ExamTime));
				var actionsCell = $('<td></td>');
				actionsCell.append($('<i class="fa fa-trash-o cur-p deleteOne"></i>').click(deleter));
				actionsCell.append($('<i class="fa fa-edit changeInfrom"></i>').click(function () {
					changeInfo.call(this); // 确保this上下文正确  
				}));
				row.append(actionsCell);
				$('#userTbody').append(row);
			});

			// 调用添加颜色的函数  
			addColor();
		},
		error: function () {
			alert('数据获取失败！');
		}
	});
});

// 修改 changeInfo 函数以支持从DOM元素触发  
function changeInfo() {
	window.changeobject = $(this).closest('tr'); // 使用closest获取最近的tr元素  
	popup("changeInfrom");
	march();
}

// 确保在文档加载时调用 fetchData 函数 

document.addEventListener('DOMContentLoaded', function() {  
    // 使用getElementsByClassName获取元素，注意返回的是HTMLCollection  
    const monthSelect = document.getElementsByClassName('month')[0];  
    const daySelect = document.getElementsByClassName('day')[0];  
    const hourSelect = document.getElementsByClassName('hour')[0];  
	const minuteSelect = document.getElementsByClassName('minute')[0];  
    const currentYear = new Date().getFullYear();  
  
    // 填充月份  
    for (let month = 1; month <= 12; month++) {  
        const option = document.createElement('option');  
        option.value = month;  
        option.textContent = month.toString().padStart(2, '0') + "月";  
        monthSelect.appendChild(option);  
    }  
  
    // 填充日期（这里简单起见，我假设每个月都是31天）  
    for (let day = 1; day <= 31; day++) {  
        const option = document.createElement('option');  
        option.value = day;  
        option.textContent = day.toString().padStart(2, '0') + "日";  
        daySelect.appendChild(option);  
    }  
  
    // 填充小时  
    for (let hour = 0; hour <= 23; hour++) {  
        const option = document.createElement('option');  
        option.value = hour;  
        option.textContent = hour.toString().padStart(2, '0') + "时";  
        hourSelect.appendChild(option);  
    }  

for (let minute = 0; minute <= 30; minute+=30) {  
	const option = document.createElement('option');  
	option.value = minute;  
	option.textContent = minute.toString().padStart(2, '0') + "分";  
	minuteSelect.appendChild(option);  
}  
});